﻿using System;
using System.Configuration;
using SimpleServiceBus.Configuration;
using SimpleServiceBus.Server.Management.EndpointMonitor;
using SimpleServiceBus.Server.Management.EndpointMonitor.MessageHandlers;

namespace SimpleServiceBus.Server.Configuration
{
    public class EndpointMonitorConfiguration : ConfigurationSection
    {
        [ConfigurationProperty("endpointMonitorInterval", IsRequired = false)]
        public TimeSpan EndpointMonitorInterval
        {
            get { return (TimeSpan) base["endpointMonitorInterval"]; }
            set { base["endpointMonitorInterval"] = value; }
        }

        [ConfigurationProperty("statusSummaryBroadcastInterval", IsRequired = false)]
        public TimeSpan StatusBroadcastInterval
        {
            get { return (TimeSpan) base["statusSummaryBroadcastInterval"]; }
            set { base["statusSummaryBroadcastInterval"] = value; }
        }

        public void Configure(IEndpointBuilder endpoint)
        {
            var monitor = endpoint.GetService<IEndpointMonitorServerService>();
            if (EndpointMonitorInterval > TimeSpan.MinValue)
                monitor.EndpointMonitorInterval = EndpointMonitorInterval;

            var aggregator = endpoint.GetService<IEndpointStatusAggregationService>();
            if (StatusBroadcastInterval > TimeSpan.MinValue)
                aggregator.StatusBroadcastInterval = StatusBroadcastInterval;
        }

        public static void ConfigureEndpointAsEndpointMonitor(IEndpointBuilder endpoint)
        {
            endpoint.RegisterService<IEndpointMonitorServerService, EndpointMonitorServer>();
            endpoint.RegisterService<IEndpointStatusAggregationService, EndpointStatusAggregationService>();

            endpoint.MessageHandlers.RegisterMessageHandlerAssembly(typeof(EndpointStatusMessageHandler).Assembly);


            EndpointMonitorConfiguration config = GetConfiguration();
            if (config != null)
                config.Configure(endpoint);
        }

        public static void ConfigureEndpointAsEndpointMonitor(IEndpointBuilder endpoint, TimeSpan monitorInterval, TimeSpan broadcastInterval)
        {
            ConfigureEndpointAsEndpointMonitor(endpoint);
            
            endpoint.GetService<IEndpointMonitorServerService>().EndpointMonitorInterval = monitorInterval;
            endpoint.GetService<IEndpointStatusAggregationService>().StatusBroadcastInterval = broadcastInterval;
        }

        public static EndpointMonitorConfiguration GetConfiguration()
        {
            return GetConfiguration("endpointMonitorServer");
        }

        public static EndpointMonitorConfiguration GetConfiguration(string sectionName)
        {
            return ConfigurationManager.GetSection(sectionName) as EndpointMonitorConfiguration;
        }
    }
}